package cn.iocoder.yudao.module.fengdong.smartelderly.utils;


import cn.iocoder.yudao.module.infra.service.file.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author zhangjiasong
 * @description: TODO
 * @date 2024/1/2 17:04
 */
@Slf4j
@Component
public class zipUtils {
    @Resource
    private FileService fileService;
    @Resource
    FastDFSClient fastDFSClient;
    private final String ROOTPATHS="C:\\testZip";
    public List<String> downloadToLocal(List<String> urls, HttpServletResponse response) throws Exception {
        // applicationProperties 来源于配置文件读取类,获取本地指定的临时存放区域
        String rootPath = ROOTPATHS;
        File file = new File(rootPath);
        if(!file.exists()){
            file.mkdirs();
        }
        List<String> fileList = new ArrayList<>();
        try {
            File f = null;
            FileOutputStream fos = null;
            ZipOutputStream zos = null ;
            for(String url : urls){
                String fileName = url.substring(url.lastIndexOf("/")+1);
                // 读取内容
//                byte[] content = fileService.getFileContent(18L, url);
                URL httpUrl = new URL(url);
                HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(3 * 1000);
                InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
                byte[] content = readInputStream(inStream);//得到图片的二进制数据

                fileList.add(rootPath + "//" + fileName+".jpg");
                f = new File(rootPath + "//" + fileName+".jpg");
                fos = new FileOutputStream(f);
                fos.write(content,0,content.length);
            }
            zipFile(fileList,response); //前端页面
//            zipFile(fileList);  //本地
            fos.flush();
            fos.close();
            return fileList;
        } catch (Exception e){
            throw new Exception("Batch download file failed"+this.getClass().getSimpleName()+"Batch download file failed");

        }
    }
    public void zipFile(List<String> fileUlr, HttpServletResponse response) throws Exception {
        byte [] bytes = new byte[1024];

        String zipFileName= URLEncoder.encode("图片压缩下载");
        BufferedOutputStream bos = null ;
        FileInputStream in = null;
        ZipOutputStream out = null;
        try {
            bos = new BufferedOutputStream(response.getOutputStream());

            response.reset();
            response.setContentType("application/x-msdownload");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + zipFileName + ".zip");

            out = new ZipOutputStream(bos);
            for(String str :  fileUlr) {
                File  file = new File(str);
                if(!file.exists()){
                    log.error("文件被删除");
                    continue;
                }
                ZipEntry zEntry = new ZipEntry(file.getName());
                out.putNextEntry(zEntry);
                in = new FileInputStream(file);
                byte[] buffer = new byte[1024];
                int read = 0;
                while((read = in.read(buffer)) != -1){
                    out.write(buffer, 0, read);
                }
            }
            out.close();
            bos.close();
            log.info("========= 文件压缩成功 ============");
        } catch (Exception e){
            throw new Exception("Batch download file failed"+this.getClass().getSimpleName()+"Batch download file failed");
        }
    }
    /**
     *  下载文件到制定路径
     * @param fileList
     */
    public void zipFile(List<String> fileList){

        String zipName ="批量下载.zip";
        String zipPath = ROOTPATHS + "//" + zipName;

        BufferedInputStream bis =null;
        try {
            ZipOutputStream zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipPath)));
            for(String str :  fileList) {
                File  file = new File(str);
                if(!file.exists()){
                    log.error("文件被删除");
                    continue;
                }
                ZipEntry zEntry = new ZipEntry(file.getName());
                zipOutput.putNextEntry(zEntry);
                bis = new BufferedInputStream(new FileInputStream(file));
                byte[] buffer = new byte[1024];
                int read = 0;
                while((read = bis.read(buffer)) != -1){
                    zipOutput.write(buffer, 0, read);
                }
            }
            zipOutput.finish();
            bis.close();
            zipOutput.close();

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    /**
     * 从输入流中获取数据
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }


}
